package Program.LoginUI;

import Program.AdminUI.AdminUI;
import Program.ForgetUI.ForgetUI;
import Program.Information.Admin;
import Program.Information.User;
import Program.RegisterUI.AdminRegisterUI;
import Program.RegisterUI.UserRegisterUI;
import Program.SqlTool.AdminDAO;
import Program.SqlTool.UserDAO;
import Program.Tool.CodeUtil;
import Program.Tool.Popup;
import Program.UserUI.UserUI;

import javax.swing.*;
import java.awt.event.*;
import java.sql.SQLException;

public class LoginListener implements ActionListener {
    //登录界面
    private JFrame loginUI;
    //顶端容器
    private JPanel northPanel;
    //最小化按钮
    private JButton minimizeButton;
    //关闭按钮
    private JButton closeButton;
    //登录按钮
    private JButton loginButton;
    //忘记密码按钮
    private JButton forgetButton;
    //注册按钮
    private JButton registerButton;
    //账号输入框
    private JTextField userNameField;
    //密码输入框
    private JPasswordField passwordField;
    //用户或者管理员登录选择下拉框
    private JComboBox<String> styleBox;
    //正确验证码显示区
    private JButton rightCode;
    //验证码输入框
    private JTextField codeField;
    //验证码字符串
    private String codeStr;
    //记录鼠标x轴上的位置
    private int mouseAtX = 0;
    //记录鼠标y轴上的位置
    private int mouseAtY = 0;
    //验证码输入错次数计算器
    private int codeNum = 0;

    public LoginListener() {
        super();
    }

    public LoginListener(JFrame loginUI, JPanel northPanel, JButton minimizeButton,
                         JButton closeButton, JButton loginButton, JButton forgetButton,
                         JButton registerButton, JTextField userNameField, JPasswordField passwordField,
                         JComboBox<String> styleBox, JButton rightCode, JTextField codeField, String codeStr) {
        super();
        this.loginUI = loginUI;
        this.northPanel = northPanel;
        this.minimizeButton = minimizeButton;
        this.closeButton = closeButton;
        this.loginButton = loginButton;
        this.forgetButton = forgetButton;
        this.registerButton = registerButton;
        this.userNameField = userNameField;
        this.passwordField = passwordField;
        this.styleBox = styleBox;
        this.rightCode = rightCode;
        this.codeField = codeField;
        this.codeStr = codeStr;
        this.canDraged(this.northPanel);
    }

    //设置窗口移动
    public void canDraged(JPanel p){
        //创建接收鼠标事件的监听器
        MouseAdapter mouseAdapter=new MouseAdapter() {
            //当鼠标按下时获取窗口的坐标位置
            public void mousePressed(MouseEvent e) {
                mouseAtX = e.getPoint().x;
                mouseAtY = e.getPoint().y;
            }
        };
        MouseMotionAdapter motionAdapter=new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                //设置获取拖拽后的位置并窗口的位置
                loginUI.setLocation((e.getXOnScreen()-mouseAtX),(e.getYOnScreen()-mouseAtY));
            }
        };
        //给顶部容器添加监听事件
        p.addMouseListener(mouseAdapter);
        p.addMouseMotionListener(motionAdapter);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==loginButton) {
            try {
                loginCheck();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else if(e.getSource()==closeButton) {
            System.exit(0);
        }else if(e.getSource()==minimizeButton) {
            loginUI.setExtendedState(JFrame.ICONIFIED);
        }else if(e.getSource()==registerButton) {
            // 触发注册事件
            if (styleBox.getSelectedItem().toString().equals("居民")){
                SwingUtilities.invokeLater(()->new UserRegisterUI());
            }else {
                SwingUtilities.invokeLater(()->new AdminRegisterUI());
            }
            loginUI.dispose();
        }else if(e.getSource()==forgetButton) {
            // 触发找回密码事件
            SwingUtilities.invokeLater(() -> new ForgetUI());
            loginUI.dispose();
        }else if(e.getSource() == rightCode ){
            //更新验证码
            resetCode();
        }
    }

    //登录检查
   private void loginCheck() throws SQLException {
        //从用户名框里读取用户名
       String inputUserName = userNameField.getText();
       //从密码框里读取密码
       char[] tempPassword = passwordField.getPassword();
       String inputPassword = new String(tempPassword);
       //从验证码框里读取验证码
       String inputCode = codeField.getText();
       //提示信息
       String info = "";
       if(inputUserName.isEmpty() || inputPassword.isEmpty()){
           // 判断用户名和密码是否为空
           info = "<html>用户名与密码不能为空!</html>";
           Popup.showJDialog(info);
       }else if(inputCode.isEmpty()){
           // 判断验证码是否为空
           info = "<html>验证码为空，请输入验证码!</html>";
           Popup.showJDialog(info);
       }else if(!(inputUserName.length()>=4 && inputUserName.length() <= 17)){
           //判断用户名格式是否正确，最小长度4，最大长度17
           info = "<html>用户名要求：最小长度为4，最大长度为17</html>";
           Popup.showJDialog(info);
           //清空输入框
           userNameField.setText("");
       }else if (!(inputPassword.length() >=4 && inputPassword.length() <= 17)){
           //判断密码格式是否正确，最小长度4，最大长度17
           info = "<html>密码要求：最小长度为4，最大长度为17</html>";
           Popup.showJDialog(info);
           //清空输入框
           passwordField.setText("");
       } else if (!inputCode.equalsIgnoreCase(codeStr)){
           // 判断验证码是否正确
           info = "<html>验证码错误，请重新输入!</html>";
           Popup.showJDialog(info);
           //清空验证码输入框
           codeField.setText("");
           //错误次数+1
           codeNum++;
           if(codeNum == 3){
               //更新验证码
               resetCode();
               //重置计算器
               codeNum = 0;
           }
       }else {
           if (styleBox.getSelectedItem().toString().equals("居民")){
               boolean flat = UserDAO.accountCheck(inputUserName,inputPassword);
               if (flat){
                  User user = UserDAO.selectUser(inputUserName);
                   System.out.println(user);
                   //登录成功
                   SwingUtilities.invokeLater(()->new UserUI(user));
                   loginUI.dispose();
               }else {
                   //登录失败
                   info = "<html>用户名或密码错误请重新输入！</html>";
                   Popup.showJDialog(info);
                   //清空所有输入框
                   userNameField.setText("");
                   passwordField.setText("");
                   codeField.setText("");
                   //更新验证码
                   resetCode();
                   //重置计算器
                   codeNum = 0;
               }
           }else {
               boolean flat = AdminDAO.accountCheck(inputUserName, inputPassword);
               if (flat){
                   Admin admin = AdminDAO.selectAdmin(inputUserName);
                   System.out.println(admin);
                   //登录成功
                   SwingUtilities.invokeLater(()->new AdminUI(admin));
                   loginUI.dispose();
               }else {
                   //登录失败
                   info = "<html>用户名或密码错误请重新输入！</html>";
                   Popup.showJDialog(info);
                   //清空所有输入框
                   userNameField.setText("");
                   passwordField.setText("");
                   codeField.setText("");
                   //更新验证码
                   resetCode();
                   //重置计算器
                   codeNum = 0;
               }
           }
       }
   }

   //更新验证码
    private void resetCode(){
        //获取新的验证码
        this.codeStr = CodeUtil.getCode();
        //更新显示的验证码
        this.rightCode.setText(codeStr);
    }

}
